<template>
  <div>
    <div class="main">
      <span class="unTitle">基本信息</span>
      <el-form ref="orderInfoForm" :model="formData" :inline="true" :rules="orderRules" size="mini"
               :hide-required-asterisk="true"
               label-position="left" style="margin: 15px 0 0 12px">
        <el-col :span="24">
          <el-form-item label="订单封面：" prop="orderImage">
            <el-upload id="orderImg" ref="orderImg" :class="{hide: hideUploadBtn}" :limit="1"
                       action=""
                       :http-request="orderHttpRequest"
                       :auto-upload="true"
                       :on-remove="orderImgHandleRemove"
                       :on-change="orderImgHandleCheck"
                       :on-success="orderImgHandleCheck"
                       :before-upload="imageBeforeUpload"
                       list-type="picture-card"
                       multiple
                       accept="image/*">
              <img :src="formData.imagePath" v-if="originImage" class="avatar" alt="图片" />
              <i v-else class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-form-item label="订单标题：" prop="orderTitle">
          <el-input v-model="formData.orderTitle" placeholder="请输入订单标题" clearable />
        </el-form-item>
        <el-form-item label="对图时间：" prop="orderDate" class="formElement">
          <el-date-picker
            v-model="formData.orderDate"
            type="datetime"
            clearable
            style="width: 205px"
            size="mini"
            placeholder="请选择对图时间"
            default-time="10:30:00"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="orderDatePickerOptions"
          />
        </el-form-item>
        <el-form-item label="选择客户：" prop="customerId" class="formElement">
          <el-select v-model="formData.customerId"
                     @change="changeCustomer"
                     placeholder="请选择客户" clearable>
            <el-option v-for="item in orderCustomer"
                       :key="item.id"
                       :label="item.customerName"
                       :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="派单方式：" prop="dispatchType">
          <el-radio-group v-model="formData.dispatchType"
                          @change="changeDispatchType"
                          size="medium">
            <el-radio v-for="(item, index) in dispatchMethodOptions" :key="index"
                      :value="item.value"
                      :label="item.value">{{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="制作公司：" prop="orgId" class="formElement">
          <el-select v-model="formData.orgId" placeholder="请选择制作公司" clearable
                     @change="()=>this.formData.orgName=companyInfoList.find(ci=>this.formData.orgId===ci.id).name">
            <el-option
              v-for="item in companyInfoList"
              :label="item.name"
              :value="item.id"
              :key="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="上传附件：" prop="customerServiceFactoryId" class="formElement">
          <el-button icon="el-icon-plus" disabled size="small" style="width: 45px" />
          <el-select size="small" disabled placeholder="请选择附件" clearable style="width: 150px;margin-left: 2px">r
          </el-select>
        </el-form-item>
        <el-form-item label="制作组：" v-show="formData.dispatchType===2" label-width="80px"
                      prop="teamId">
          <el-select v-model="formData.teamId" placeholder="请选择制作组" clearable
                     @change="()=>this.formData.teamName=orderMakeTeam.find(omt=>this.formData.teamId===omt.value).label">
            <el-option
              v-for="item in orderMakeTeam"
              :label="item.label"
              :value="item.value"
              :key="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="风格分类：" prop="fgfl"
                      :class="formData.dispatchType===1?null:'formElement'">
          <el-select v-model="formData.fgfl" placeholder="请选择风格" clearable
                     @change="()=>this.formData.fgflName=orderStyle.find(os=>this.formData.fgfl===os.value).label">
            <el-option
              v-for="item in orderStyle"
              :label="item.label"
              :value="item.value"
              :key="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单类型：" class="formElement" prop="orderType">
          <el-select v-model="formData.orderType" placeholder="请选择订单类型" clearable>
            <el-option label="施工图" :value="1"></el-option>
            <el-option label="漫游图" :value="2"></el-option>
            <el-option label="效果图" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单品质：" :class="formData.dispatchType===2?null:'formElement'" prop="orderQuality">
          <el-select v-model="formData.orderQuality" placeholder="请选择订单品质" clearable
                     @change="()=>this.formData.orderQualityName=orderQuality.find(quality=>this.formData.orderQuality===parseInt(quality.value)).label">
            <el-option
              v-for="item in orderQuality"
              :key="item.id"
              :label="item.label"
              :value="parseInt(item.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="完成时间：" prop="finishDate" :class="formData.dispatchType===1?null:'formElement'">
          <el-date-picker
            v-model="formData.finishDate"
            type="datetime"
            clearable
            style="width: 205px"
            size="mini"
            placeholder="请选择完成时间"
            default-time="14:30:00"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="finishDatePickerOptions"
          />
        </el-form-item>
        <el-form-item label="备注：" prop="remark" label-width="81px" class="formElement">
          <el-input v-model="formData.remark" :rows="2" style="width: 208px" type="textarea"
                    placeholder="请输入..." clearable />
        </el-form-item>
      </el-form>
      <span class="unTitle">订单金额</span>
      <div style="margin: 10px 0 20px 40px">
        <span style="font-size: 12px;color: #838383;">订单金额：</span>
        <el-input-number v-model="formData.money" size="mini" controls-position="right" :min="formData.paidMoney"
                         :step="100" style="width: 105px;" />
        <span class="coupon">已付金额：</span>
        <el-input-number v-model="formData.paidMoney" size="mini" controls-position="right" :min="0"
                         :max="formData.money" :step="100" style="width: 105px;" />
        <span class="coupon">待支付金额：</span>
        <el-input-number v-model="setPayment" size="mini" controls-position="right" :min="formData.payment"
                         :max="formData.payment" style="width: 105px;" />
        <span class="coupon">优惠券：</span>
        <el-select v-model="preferentialId" class="customerCoupon" style="width: 220px" size="small"
                   placeholder="请选择优惠券"
                   clearable @change="changeCustomerCoupon">
          <template slot="prefix" v-if="preferentialId!==''">
            <el-tag size="mini" type="warning">{{ chooseCouponMoney + "元" }}</el-tag>
          </template>
          <el-option :value="null" label="无优惠券" v-if="customerCouponList.length===0" />
          <el-option v-for="item in customerCouponList"
                     v-else
                     :label='item.name'
                     :value="item.id"
                     :key="item.id">
            {{ item.name }}&nbsp;&nbsp;
            <el-tag size="mini" type="warning">{{ item.money + "元" }}</el-tag>
          </el-option>
        </el-select>
      </div>
      <div style="margin-top: 20px">
        <span style="display: block;margin-bottom: 5px">
          <span class="unTitle">订单任务</span>
          <el-popover placement="top" width="240px" v-model="batchAddBtnVisible">
            <span>批量添加&nbsp;&nbsp;
              <el-input-number v-model="addTaskCount"
                               size="mini"
                               controls-position="right"
                               :min="1" :step="1" :max="10"
                               style="width: 80px;" />&nbsp;&nbsp;个任务
              <el-button type="primary" size="mini" @click="addTask">确定</el-button>
            </span>
            <el-button style="margin-left: 885px" size="mini" slot="reference">批量添加</el-button>
          </el-popover>&nbsp;&nbsp;
          <el-button type="primary" size="mini" @click="addTask(1)">添加任务</el-button>
        </span>
        <ul class="infinite-list">
          <li class="infinite-list-item" v-if="taskArray.length===0" style="justify-content: center;
                                height: 120px;font-size: 14px;color: gray">
            -暂无任务-
          </li>
          <el-form ref="taskForm" :inline="true" class="taskFrom"
                   :hide-required-asterisk="true">
            <li v-for="(item,index) in taskArray" class="infinite-list-item list-item" :key="index">
              <span style="font-family: Segoe UI Black,serif;font-size: 18px;color: gray;margin-left: 30px">
                {{ index < 9 ? '0' + (parseInt(index) + 1) : parseInt(index) + 1 }}
              </span>
              <span>
                <el-upload
                  :class="['taskUpload',{isShowTaskBtn:item.isTaskBtn}]"
                  :limit="1"
                  action=""
                  :http-request="param=>taskHttpRequest(param,item)"
                  :auto-upload="true"
                  list-type="picture-card"
                  :on-success="(file, fileList)=>taskImgHandleCheck(file, fileList,item)"
                  :on-change="(file, fileList)=>taskImgHandleCheck(file, fileList,item)"
                  :on-remove="(file, fileList)=>taskImgHandleRemove(file, fileList,item)"
                  :before-upload="imageBeforeUpload"
                  multiple
                  accept="image/*">
                 <img :src="item.imagePath" class="taskUploadImg" v-if="item.originImage" alt="图片" />
                  <i class="el-icon-plus" v-else></i>
                </el-upload>
              </span>
              <div style="height: 100px;width: 700px">
                <el-form-item label="任务名称" prop="taskName" style="padding-top: 4px" class="inputSpan">&nbsp;&nbsp;&nbsp;
                  <el-input style="width: 200px;height: 25px"
                            v-model="item.taskName" placeholder="请输入任务名称"
                            clearable size="mini" />
                </el-form-item>
                <el-form-item label="任务金额" prop="money" style="padding-top: 4px" class="inputSpan">&nbsp;&nbsp;&nbsp;
                  <el-input-number v-model="item.money" size="mini" placeholder="金额"
                                   controls-position="right"
                                   :min="100" :step="100"
                                   style="width: 100px;" />
                </el-form-item>
                <el-form-item label="场景分类" prop="gnfl" class="inputSpan">&nbsp;&nbsp;&nbsp;
                  <el-cascader v-model="item.gnflArray" :options="orderCategoryList" clearable
                               placeholder="请选择场景分类"
                               size="mini" style="width: 160px"
                               @change="temp=>changeTaskFgfl(temp,item)"
                               :props="{label:'name',value:'id',children:'gradeOrderCategory' }" />
                </el-form-item>
                <el-form-item label="图片类型" prop="makeType" class="inputSpan">&nbsp;&nbsp;&nbsp;
                  <el-select v-model="item.makeType"
                             placeholder="请选择图片类型"
                             size="mini"
                             style="width: 140px">
                    <el-option label="静态图" :value="1" />
                    <el-option label="全景图" :value="2" />
                  </el-select>
                </el-form-item>
              </div>
              <span style="margin-left: 40px">
                <el-button size="mini" type="danger" @click="taskArray.splice(index,1)">删除</el-button>
              </span>
            </li>
          </el-form>
        </ul>

      </div>
      <div style="margin: 20px 0 30px 15px">
        <el-button type="primary" v-if="isInsetOrUpd==='true'" size="mini"
                   @click="orderInsertSubmitBtn">确认创建
        </el-button>
        <el-button type="primary" v-else size="mini" @click="orderUpdateBtn">确认修改</el-button>
        <el-button @click="$router.back()" size="mini">取消</el-button>
      </div>
    </div>
  </div>
</template>

<script>
  import {mapState} from "vuex";
  import {
    queryTotalLevelOrderCategory,
    orderUploadFile,
    queryCustomerCoupon,
    useCustomerCoupon,
    insertOrderInfo, updateOrderAndTask, queryOrderDetailByOrderId
  } from "@/api/orderInfo";
  import Cookies from "js-cookie";

  export default {
    name: 'CreateOrderView',
    data() {
      //制作组下拉框自定义表单校验
      let checkingTeamId = (rule, value, callback) => {
        if (this.formData.dispatchType === 2) {
          if (!this.formData.teamId) {
            callback(new Error('请选择制作组'));
          } else {
            callback();
          }
        }
        callback();
      };

      return {
        userInfo: JSON.parse(Cookies.get("JavaInfo")),
        formData: {
          orderTitle: "",
          customerId: "",
          customerName: "",
          teamId: "",
          teamName: "",
          dispatchType: 1,
          orgId: "",
          orgName: "",
          fgfl: "",
          fgflName: "",
          orderDate: "",
          finishDate: "",
          orderType: "",
          customerServiceId: 0,
          customerServiceName: "",
          salesmanId: 0,
          salesmanName: "",
          orderQuality: "",
          orderQualityName: "",
          remark: null,
          money: 500,
          paidMoney: 0,
          payment: this.setPayment,
          image: "",
          imagePath: "",
          preferentiMoney: 0,
          orderDetailList: []
        },
        orderDatePickerOptions: {
          disabledDate: time => {
            return time.getTime() < Date.now() - 8.64e7;
          },
        },
        finishDatePickerOptions: {
          disabledDate: time => {
            return time.getTime() < Date.now();
          },
        },
        orderRules: {
          orderTitle: [{required: true, message: '请输入订单标题', trigger: 'blur'}],
          orderDate: [{required: true, message: '请选择订单对图时间', trigger: 'blur'}],
          customerId: [{required: true, message: '请选择客户', trigger: 'change'}],
          orgId: [{required: true, message: '请选择制作公司', trigger: 'change'}],
          fgfl: [{required: true, message: '请选择订单风格', trigger: 'change'}],
          orderType: [{required: true, message: '请选择订单类型', trigger: 'change'}],
          teamId: [{validator: checkingTeamId, trigger: 'change'}],
          orderQuality: [{required: true, message: '请选择订单品质', trigger: 'change'}],
          finishDate: [{required: true, message: '请选择完成订单时间', trigger: 'blur'}]
        },
        dispatchMethodOptions: [
          {'label': '派单员派送', 'value': 1},
          {'label': '直接派送', 'value': 2}
        ],
        hideUploadBtn: false,
        useCoupon: false,
        uploadImgFileList: [],
        taskArray: [],
        batchAddBtnVisible: false,
        addTaskCount: 0,
        orderCategoryList: [],
        orderImgUid: null,  //记录订单图片uid
        customerCouponList: [],     //用户优惠券
        preferentialId: "",         //优惠券Id
        isInsetOrUpd: true,   //修改页面还是新增页面,true新增,false反之
        originImage: false,
        chooseCouponMoney: 0,
      }
    },
    computed: {
      ...mapState({
        orderStyle: state => state.order.orderStyle,
        orderMakeTeam: state => state.order.orderMakeTeam,
        companyInfoList: state => state.order.companyInformation,
        orderCustomer: state => state.order.orderCustomer,
        orderQuality: state => state.order.orderQuality,
      }),
      setPayment() {
        let payment = this.formData.money - this.formData.paidMoney - this.chooseCouponMoney
        if (payment < 0) payment = 0;
        this.formData.payment = payment;
        return payment;
      },
    },
    methods: {
      initialization() {
        this.$store.dispatch("order/queryOrderStyle");
        this.$store.dispatch("order/queryOrderTeam");
        this.$store.dispatch("order/queryCompanyInfo");
        this.$store.dispatch("order/queryCustomerInformation");
        this.$store.dispatch("order/queryOrderAttachmentType");
        this.$store.dispatch("order/queryOrderQuality");
        queryTotalLevelOrderCategory().then(data => this.orderCategoryList = data);
        queryCustomerCoupon(this.userInfo.id).then(data => this.customerCouponList = data);
      },
      orderImgHandleCheck(file, fileList) {
        this.hideUploadBtn = fileList.length >= 1;
        this.formData.originImage = false;
      },
      orderImgHandleRemove(file, fileList) {
        this.hideUploadBtn = fileList.length >= 1;
        this.uploadImgFileList = this.uploadImgFileList.filter(item => item.uid !== this.orderImgUid);
        this.formData.originImage = true;
        this.formData.image = null;
      },
      orderHttpRequest(param) {
        this.uploadImgFileList.push(param.file)
        this.formData.image = param.file.name;
        this.orderImgUid = param.file.uid;
      },
      taskImgHandleCheck(file, fileList, item) {
        item.isTaskBtn = fileList.length >= 1;
        item.originImage = false;
        this.$forceUpdate();
      },
      taskImgHandleRemove(file, fileList, item) {
        setTimeout(() => {
          item.isTaskBtn = fileList.length >= 1;
          this.$forceUpdate();
        }, 980);
        this.uploadImgFileList = this.uploadImgFileList.filter(temp => temp.uid !== item.imageUid);
        if (item.imagePath != null) item.originImage = true;
      },
      taskHttpRequest(param, item) {
        this.uploadImgFileList.push(param.file)
        item.image = param.file.name;
        item.imageUid = param.file.uid;
      },
      changeCustomer() {
        let result = this.orderCustomer.find(cus => this.formData.customerId === cus.id);
        this.formData.customerName = result.customerName;
        this.formData.customerServiceId = result.serviceId;
        this.formData.customerServiceName = result.serviceName;
      },
      changeDispatchType() {
        this.formData.teamId = "";
        this.formData.teamName = "";
      },
      imageBeforeUpload(file) {
        let isAccept = new RegExp('image/*').test(file.type)
        let isSize = file.size / 1024 / 1024 / 1024 < 2;
        if (!isAccept) {
          this.$message.error('应该选择图片类型的文件')
        }
        if (!isSize) {
          this.$message.error('上传图片大小不能超过 2G!');
        }
        return isAccept
      },
      addTask(num) {
        let task = {
          taskName: "", money: 500, gnflArray: [], gnfl: "", gnflName: "",
          makeType: 1, image: null, imageUid: null, isTaskBtn: false
        }
        if (num === 1) {
          this.taskArray.push(task)
        } else {
          for (let i = 1; i <= this.addTaskCount; i++) {
            this.taskArray.push(task)
          }
          this.batchAddBtnVisible = false
        }
      },
      changeTaskFgfl(temp, item) {
        let finds = this.orderCategoryList.find(ocl => ocl.id === temp[0]);
        let result = finds.gradeOrderCategory.find(ocl => ocl.id === temp[1]);
        item.sceneId = finds.id;
        item.sceneName = finds.name;
        item.gnfl = result.id;
        item.gnflName = result.name;
      },
      uploadOrderAndTaskFile() {
        let form = new FormData()
        this.uploadImgFileList.forEach(file => {
          form.append('files', file)
        })
        orderUploadFile(form);
      },
      changeCustomerCoupon() {
        if (this.preferentialId !== '' && this.preferentialId !== null) {
          this.customerCouponList.forEach(item => {
            if (item.id === this.preferentialId) {
              this.formData.preferentiMoney += item.money
              this.chooseCouponMoney = item.money;
            }
          })
        } else {
          this.formData.preferentiMoney = this.formData.payMoney;
          this.chooseCouponMoney = 0;
        }
      },
      orderInsertSubmitBtn() {
        this.$refs['orderInfoForm'].validate(valid => {
          if (valid) {
            this.formData.orderDetailList = this.taskArray;
            this.formData.salesmanId = this.userInfo.id;
            this.formData.salesmanName = this.userInfo.realName;
            this.uploadOrderAndTaskFile()
            if (this.preferentialId !== null && this.preferentialId !== "") useCustomerCoupon(this.preferentialId);
            insertOrderInfo(this.formData)
              .then(resp => {
                this.$message.success('订单创建成功！')
                this.$router.push({path: '/order/orderOpenSea'})
              });
            console.log(this.formData)
          } else {
            this.$message.warning("请完善需求信息")
          }
        })
      },
      orderUpdateBtn() {
        this.$refs['orderInfoForm'].validate(valid => {
          if (valid) {
            this.formData.orderDetailList = this.taskArray;
            this.formData.money += this.formData.discountedAmount;
            console.log(this.formData)
            console.log(this.uploadImgFileList)
            if (this.uploadImgFileList.length > 0) this.uploadOrderAndTaskFile();
            if (this.preferentialId != null && this.preferentialId !== "") useCustomerCoupon(this.preferentialId);
            updateOrderAndTask(this.formData).then(resp => {
              this.$message.success({message: '修改成功！', duration: 1500});
              this.$router.push({path: '/order/orderOpenSea'});
            })
          }
        })
      }
    },
    async mounted() {
      this.initialization();
      this.isInsetOrUpd = this.$route.params.isInsOrUpd;
      if (this.isInsetOrUpd === 'false') {
        this.formData = JSON.parse(decodeURIComponent(this.$route.params.orderInfo)) || sessionStorage.getItem("handleOrder_orderInfo");
        this.formData.fgfl = this.formData.fgfl.toString();
        this.formData.teamId = this.formData.teamId.toString();
        this.formData.discountedAmount = this.formData.preferentiMoney;
        this.formData.imagePath = this.formData.image;
        this.formData.image = null;
        this.formData.money = this.formData.money - this.formData.preferentiMoney;
        this.originImage = true;
        await queryOrderDetailByOrderId(this.formData.id).then(data => {
          this.$set(this.formData, 'orderDetailList', data);
        })
        this.formData.orderDetailList.forEach(item => {
          item.gnflArray = [item.sceneId, item.gnfl];
          item.originImage = false;
          if (item.image != null && item.image !== "") {
            item.imagePath = item.image;
            item.image = null;
            item.originImage = true;
          }
          item.imageUid = null;
          item.isTaskBtn = false;
        })
        this.taskArray = this.formData.orderDetailList;
      }
    },
  }


</script>

<style>
  .main {
    margin: 25px 0 0 20px;
  }

  .unTitle {
    font-size: 15px;
    font-weight: bold;
    display: inline-block;
    margin: 5px 0;
  }

  #orderImg .el-upload--picture-card {
    width: 60px;
    height: 40px;
    line-height: 50px;
    margin-bottom: 5px;
    position: relative;
    top: -5px;
  }

  #orderImg .el-upload-list--picture-card .el-upload-list__item-thumbnail {
    width: 60px !important;
    height: 40px !important;

  }

  .avatar {
    width: 61px;
    height: 38px;
  }

  #orderImg .el-upload-list--picture-card .el-upload-list__item-actions {
    width: 60px !important;
    height: 40px !important;
  }

  #orderImg .el-upload-list--picture-card .el-upload-list__item {
    width: 60px !important;
    height: 40px !important;
    position: relative;
    top: -5px;
  }

  .formElement {
    margin-left: 80px;
  }

  .coupon:not(:first-child) {
    font-size: 12px;
    color: #838383;
    margin-left: 60px;
  }

  .infinite-list {
    height: 400px;
    padding: 0;
    margin: 0;
    list-style: none;
    overflow: auto;
  }

  .infinite-list-item {
    display: flex;
    align-items: center;
    height: 130px;
    background: #dbdada;
    margin: 10px;
  }

  .list-item:hover {
    background: #B9B8B8EC;
  }

  .inputSpan:nth-child(even) {
    display: inline-block;
    font-size: 14px;
    color: gray;
    margin-left: 100px;
  }

  .inputSpan:nth-child(odd) {
    display: inline-block;
    font-size: 14px;
    color: gray;
    margin-left: 70px;
  }

  .taskFrom .el-form-item {
    margin-bottom: 20px;
  }

  .taskFrom .el-form-item__error {
    left: 15px;
  }


  /*滑动块宽度*/
  .el-switch .el-switch__core, .el-switch .el-switch__label {
    width: 40px !important;
    margin-left: 5px;
    position: relative;
    top: -1px;
  }

  .hide .el-upload--picture-card {
    display: none;
  }

  .el-form-item--mini.el-form-item:first-child {
    margin-bottom: 2px;
  }

  .isShowTaskBtn .el-upload--picture-card {
    display: none;
  }

  .taskUpload .el-upload--picture-card {
    width: 150px;
    height: 100px;
    line-height: 100px;
    margin-left: 50px;
  }

  .taskUpload .el-upload-list--picture-card .el-upload-list__item-thumbnail {
    width: 150px;
    height: 100px;
  }

  .taskUpload .el-upload-list--picture-card .el-upload-list__item-actions {
    width: 150px;
    height: 100px;
  }

  .taskUploadImg {
    width: 150px;
    height: 100px;
  }

  .taskUpload .el-upload-list--picture-card .el-upload-list__item {
    width: 150px;
    height: 100px;
    margin-left: 50px;
    margin-top: 12px;
  }

  .customerCoupon .el-input--prefix .el-input__inner {
    padding-left: 15px;
  }

  .customerCoupon .el-input__prefix {
    left: 135px;
    top: 4px;
  }
</style>
